package com.lcy.lambda.function;

import java.util.function.IntBinaryOperator;
import java.util.function.IntPredicate;

/**
 * 通过两个例子进一步理解lambda
 * @author lcy
 * @date 2024/8/15 14:59
 */
public class Demo2 {

    /**
     * 这个方法提供了两个参数的操作，可能是两个数之和，之差，之积，或者更复杂的方法。 方法operator.applyAsInt的实现由调用者自己决定
     * @param operator
     * @return
     */
    public static int calculateNum(IntBinaryOperator operator){
        int a = 10;
        int b = 20;
        return operator.applyAsInt(a, b);
    }

    /**
     * @description IntPredicate就是传入一个int参数，然后返回一个boolean，具体对这个参数做什么判断，调用者自己去实现
     *
     * @param predicate
     * @author lichenyue
     * @date 2024/08/15 15:20
     * @version 1.0
     * @return
     **/
    public static void printNum(IntPredicate predicate){
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for (int i : arr) {
            if(predicate.test(i)){
                System.out.println(i);
            }
        }
    }

    public static void main(String[] args) {
        //=========== 匿名内部类 ======================
        //计算两个数的和
        int a = calculateNum(new IntBinaryOperator() {
            @Override
            public int applyAsInt(int left, int right) {
                return left + right;
            }
        });
        System.out.println(a);

        //计算两个数的积
        int b = calculateNum(new IntBinaryOperator() {
            @Override
            public int applyAsInt(int left, int right) {
                return left * right;
            }
        });
        System.out.println(b);

        //打印偶数
        printNum(new IntPredicate() {
            @Override
            public boolean test(int value) {
                return 0 == value%2;
            }
        });

        //=========== lambda ======================
        //计算两个数的和
        System.out.println(calculateNum((int left, int right) -> left + right));

        //计算两个数的积
        System.out.println(calculateNum((int left, int right) -> left * right));

        //打印奇数
        printNum((int value) -> {
            return 0 == value%2;
        });

        //=========== 最简lambda ======================

        //计算两个数的和
        System.out.println(calculateNum((left,right) -> left + right));

        //计算两个数的积
        System.out.println(calculateNum((left,right) -> left * right));

        //打印奇数
        printNum(value -> 0 == value%2);






    }

}
